package cn.xo68.boot.auth.client.service.impl;

import cn.xo68.boot.auth.client.configuration.SecurityClient;
import cn.xo68.boot.auth.client.properties.AuthProviderProperties;
import cn.xo68.boot.auth.client.service.OauthUserService;
import cn.xo68.boot.auth.core.common.AuthConstants;
import cn.xo68.boot.auth.core.domain.Oauth2Principal;
import cn.xo68.boot.auth.core.domain.OauthResource;
import cn.xo68.core.entity.JsonResponsEntity;
import cn.xo68.core.util.JsonUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import org.apache.oltu.oauth2.common.OAuth;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class OauthUserServiceImpl implements OauthUserService {

    @Autowired
    private JsonUtil jsonUtil;

    @Autowired
    private AuthProviderProperties authProviderProperties;

    @Autowired
    private SecurityClient securityClient;

    @Cacheable(value = AuthConstants.CACHE_NAME_CLIENT_USERINFO,key = "#token",unless = "#result == ''")
    @Override
    public Oauth2Principal getPrincipal(String token) throws OAuthProblemException, OAuthSystemException {
        Oauth2Principal responsEntity = securityClient.getResource(authProviderProperties.getRootUri()+authProviderProperties.getUserInfoUri(),
                token,
                OAuth.HttpMethod.GET,
                jsonUtil.getJavaType(new TypeReference<Oauth2Principal>() {
                }));
        return responsEntity;
    }

    @Cacheable(value = AuthConstants.CACHE_NAME_CLIENT_RESOURCE,key = "#token",unless = "#result == ''")
    @Override
    public List<OauthResource> getResources(String token) throws OAuthProblemException, OAuthSystemException{
        List<OauthResource> responsEntity = securityClient.getResource(authProviderProperties.getRootUri()+authProviderProperties.getResourceUri(),
                token,
                OAuth.HttpMethod.GET,
                jsonUtil.getCollectionJavaType(List.class,OauthResource.class));
        return responsEntity;
    }
}
